<!-- 电站列表 -->
<template>
  <div class="content">
    <h4 id="title">{{ $t('licence.pow_Title')}}</h4>
    <div class="main">
      <div class="time-box">
        <!-- 电站状态 -->
        <el-select style="margin: 0 20px" v-model="powerState" :placeholder="$t('licence.status')" clearable
          @change="powerStateChanged">
          <el-option v-for="item in options" :key="item.key" :label="$t('licence.sta_type' + item.key)" :value="item.key">
          </el-option>
        </el-select>
        <!-- 国家 -->
        <el-select v-hasPermi="['index:powerstaion:show']" v-model="regionCode" :placeholder="$t('licence.guojia')" clearable @change="getAdd"
          style="margin-right: 10px">
          <el-option v-for="item in country" :key="item.id" :label="lang == 1 ? item.regionNameEn : item.cityName"
            :value="item.id">
          </el-option>
        </el-select>
        <!-- 电站地点 -->
        <el-cascader v-if="showCountry" :placeholder="$t('licence.pow_shengfen')" v-model="label" :options="addOptions" clearable
          @change="addOptionsChanged"></el-cascader>
        <el-input class="input" v-model="powerName"></el-input>
        <el-button @click="onSubmit" type="primary" style="margin: 20px 0">{{
          $t('licence.fau_Thequery')}}</el-button>
      </div>
      <el-row style="margin-bottom: 10px;" v-if="individual == 0">
        <el-col :span="1.5">
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>{{ $t('licence.sta_export')}}
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格  -->
      <el-table :data="powerStationList" v-loading="loading" @expand-change="change"
        :expand-row-keys="expandsRowId" :row-key="getRowKeys">
        <el-table-column type="expand" width="80" :label="$t('licence.pow_zhankai')">
          <template #default="{ row }">
            <div class="expand">
              <div class="expand-left">
                <div ref="chart4" style="height: 350px"></div>
              </div>
              <div class="expand-right">
                <div style="margin-left: 40px">
                  <h4 id="title" style="margin-top: 20px; margin-bottom: 30px">
                    {{ $t('licence.sys_equipmentInformation')}}
                  </h4>
                  <ul>
                    <li class="fault-content" @click="gotoStatus(row, 1)">
                      <p class="img-l">
                        <img src="../assets/images/dian-pic-09.png" alt="" />
                      </p>
                      <div class="content-r">
                        <p class="number" v-if="row.changeData">
                          {{ row.changeData.normalNo }}
                          <!-- {{ normalNo }} -->
                        </p>
                        <h4 class="small-title">
                          {{ $t('licence.dia_normal')}}
                        </h4>
                      </div>
                    </li>
                    <li class="fault-content" @click="gotoStatus(row, 2)">
                      <p class="img-l">
                        <img src="../assets/images/dian-pic-10.png" alt="" />
                      </p>
                      <div class="content-r">
                        <p class="number" v-if="row.changeData">
                          {{ row.changeData.faultNo }}
                        </p>
                        <h4 class="small-title">
                          {{ $t('licence.dia_fault')}}
                        </h4>
                      </div>
                    </li>
                    <li class="fault-content" @click="gotoStatus(row, 4)">
                      <p class="img-l">
                        <img src="../assets/images/dian-pic-11.png" alt="" />
                      </p>
                      <div class="content-r">
                        <p class="number" v-if="row.changeData">
                          {{ row.changeData.warningNo }}
                        </p>
                        <h4 class="small-title">
                          {{ $t('licence.dia_alert')}}
                        </h4>
                      </div>
                    </li>
                    <li class="fault-content" @click="gotoStatus(row, 3)">
                      <p class="img-l">
                        <img src="../assets/images/dian-pic-12.png" alt="" />
                      </p>
                      <div class="content-r">
                        <p class="number" v-if="row.changeData">
                          {{ row.changeData.offlineNo }}
                        </p>
                        <h4 class="small-title">{{ $t('licence.dia_line')}}</h4>
                      </div>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" align="center" :label="$t('licence.fau_num')" width="80">
        </el-table-column>
        <el-table-column align="center" prop="stationName" :label="$t('licence.stationName')">
          <template #default="{ row }">
            <div style="cursor: pointer; color: #305add" @click="goToStation(row)">
              {{ row.stationName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="userName" :label="$t('licence.pow_userName')" width="90">
        </el-table-column>
        <el-table-column align="center" prop="phone" :label="$t('licence.pow_phone')" width="120">
        </el-table-column>
        <el-table-column align="center" width="190" prop="email" :label="$t('licence.pow_email')">
        </el-table-column>
        <el-table-column align="center" width="210" prop="address" :label="$t('licence.pow_add')" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column align="center" prop="installedCapacity" :label="$t('licence.installedPower')" width="120">
        </el-table-column>
        <el-table-column align="center" prop="state" :label="$t('licence.currentState')" width="120">
          <template #default="scope">
            <p v-if="scope.row.state == 0">{{ $t('licence.sta_type1')}}</p>
            <p v-if="scope.row.state == 1">{{ $t('licence.sta_type2')}}</p>
            <p v-if="scope.row.state == 2">{{ $t('licence.sta_type3')}}</p>
            <p v-if="scope.row.state == 3">{{ $t('licence.sta_type4')}}</p>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="days" :label="$t('licence.pow_day')" width="150">
        </el-table-column>
        <el-table-column align="center" :label="$t('licence.fau_operation')" v-if="individual == 0" width="200">
          <template #default="scope">
            <el-button
              @click="goToDTU(scope.row)" type="text" size="small"
              style="color: #305add;">{{ $t('licence.fau_gateway')}}</el-button>
            <el-button @click="goToStation(scope.row)" type="text" size="small" style="color: #305add;">{{ $t('licence.fau_Toview')}}</el-button>
            <el-button @click="editStation(scope.row)" type="text" size="small" style="color: #305add;">{{ $t('licence.modify')}}</el-button>
            <el-button @click="delPowerStation(scope.row)" type="text" size="small" style="color: #ff1c14;">{{ $t('licence.del')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 显示隐藏 -->

      <!-- 分页 -->
      <div class="block" style="margin: 20px">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryData.page" :page-size="queryData.pageSize" :page-sizes="[2, 4, 6, 8, 10]"
          layout=" prev, pager, next,total, jumper" :total="queryData.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="PowerStationList">
import * as echarts from "echarts";
import { getStationState, getstationCurve } from "@/api/dianzhan";
import { getstationList, getAdds, getCountrys } from "@/api/homeIndex";
import { delPowerStations } from "@/api/powerStation/powerStation";
import auth from "@/plugins/auth"
import { useI18n } from 'vue-i18n'
import useStationStore from '@/store/modules/station'
const { t } = useI18n()
      const showCountry=ref(false);
      const router =useRouter()
      const { proxy } = getCurrentInstance() as ComponentInternalInstance;
      const stationStore = useStationStore();
      const loading =ref(true) //加载状态
      const powerStation = ref({}) //获取保存电站信息
      // 下拉选择状态
      // 查询状态
      const powerState = ref(0) //查询下拉绑定默认字段
      const options = [
        {key: 0,},{key: 1,},{key: 2,},
        {key: 3,},{key: 4,}
      ]
      // 地址
      const label = ref([])
      const addOptions = ref([])
      //国家
      const country = ref([{
        id:-1,
        regionNameEn:'',
        cityName:'',
      }])
      const regionCode = ref('')

      const powerName = ref('') //input输入
      const individual = ref<string | number>(0)
      // 表格信息
      const powerStationList = ref([
        {
          changeData:null,
          id:-1
        }
      ])
      // 分页
      const queryData = reactive({
        page: 1, // 当前页码
        pageSize: 10,
        total: 0, // 总数
      })
      //   设备信息
      const StationStateList = ref('') //设备信息
      const option_chart4 = ref({})
      // ======
      const ID = ref('') //保存单个电站id
      const expandsRowId = ref<string[]>([])
      const lang = ref(0)
      const userInfo = ref({
        dept:{
          countryCode:''
        },
        admin:'',
        userId:-1
      });//用户信息
      const goStationDetail = (page:string,row:any)=>{
        stationStore.setPowerInfo(row)
        // router.go(0)
        router.push({ name: 'EstablishDianZhan' })
        // router.push('/establishDianZhan')
      }
    /** 导出按钮操作 */
    const handleExport = ()=>{
      loading.value = true;
      let query = {
        address: label.value.join(","),
        pageNo: 1,
        pageSize: 1000000,
        searchValue: powerName.value,
        state: powerState.value - 1,
        country: regionCode.value,
        quickSearch: true,
      };
      // 为空不做任何操作
      if(powerStationList.value.length == 0) {
          loading.value = false;
          return ElMessage.error(t('licence.none'));
      }
       proxy?.download(
        "overview/export",
        {
          ...query,
        },
        `station_${new Date().getTime()}.xlsx`
      );
      loading.value = false;
    }
    // 页面跳转电站监控查询状态
    const gotoStatus = (row:any, key:any) =>  {
      // 存到本地存储
      stationStore.setPowerInfo(row)
      // router.go(0)
      // 跳转页面
      router.push({
        name: "Inveter",
        query: {
          statusKey: key,
        },
      });
    }
    // 展开一行
    const getRowKeys= (row:any) => {
      return row.id;
    }
    // 显示隐藏的内容曲线图和设备信息 row当前行数据  expandedRows展开数据expandedRows
    const  change = async(row:any, expandedRows:any)=> {
      ID.value = row.id; //保存单个id
      if (expandedRows.length) {
        expandsRowId.value = [];
        inpom();
        if (row) {
          expandsRowId.value.push(row.id);
          // 获取曲线图
          const { data } = await getstationCurve({
            stationId: row.id,
            type: 1,
            lang: lang.value,
          });
          nextTick(() => {
            getTrendcurveData(data);
          });
        }
      } else {
          expandsRowId.value = [];
        }
    }
    //设备信息获取
    const inpom = async()=>{
      const { data } = await getStationState({
        stationId: ID.value,
      });
      powerStationList.value.forEach((item) => {
        if (item.id == Number(ID.value)) {
          item.changeData = data;
        }
      });
      powerStationList.value = powerStationList.value.slice(0);
      StationStateList.value = data;
    }
    // 获取国家
    const  getCountry = async()=>{
      let res = await getCountrys({});
      country.value = res.data;
    }
    // 省市级选择
    const  getAdd = async(value:string) => {
      regionCode.value = value;
      let res = await getAdds({
        code: regionCode.value || userInfo.value.dept.countryCode,
        lang: lang.value,
      });
      addOptions.value = res.data;
    }
    // 获取电站列表 ===查询按钮
    const  getpower = async()=>{
      loading.value = true;
      let userId;
      if (localStorage.getItem('userType') === '1') {
        userId = userInfo.value.userId
      }
      let query = {
        address: label.value.join(","),
        pageNum: queryData.page,
        pageSize: queryData.pageSize,
        // stationName: powerName.value,
        searchValue: powerName.value,
        state: powerState.value - 1,
        country: regionCode.value,
        quickSearch: true,
        userId: userId
      };
      const res = await getstationList(query);
      powerStationList.value = res.rows;
      powerStationList.value.forEach((item) => {
        item.changeData = null;
      });
      queryData.total = res.total;
      loading.value = false;
    }
    // 查询功能
    const onSubmit = ()=>{
      getpower();
    }
    // 状态下拉选择事件
    const powerStateChanged = (value:number) => {
      powerState.value = value;
      getpower();
    }
    // 地址下拉选择事件
    const addOptionsChanged = (value:any) =>  {
      label.value = value;
      getpower();
    }
    // 查看DTU
    const goToDTU = (row) => {
      // 存到本地存储
      stationStore.setPowerInfo(row)
      // 跳转页面
      if(row.stationType == 3) router.push({ path: 'equipmentList', query: { id: row.id } })
      else router.push({ path: 'gatewayList', query: { id: row.id } })
    }
    // 查看电站
    const goToStation = (row) => {
      // 存到本地存储
      stationStore.setPowerInfo(row)
      // 跳转页面
      router.push("/dianzhan");
    }
    // 修改电站
    const editStation = (row) => {
      // 存到本地存储
      stationStore.setPowerInfo(row)
      // 跳转页面
      router.push({ path: 'powerStation', query: { id: row.id }})
    }
    // 删除电站
    const delPowerStation = async(item:any)=> {
      ElMessageBox.confirm(
        ("licence.SubmitDelPowerStation"),
        ("licence.Tips"),
        {
          confirmButtonText: ("licence.del"),
          cancelButtonText: ("licence.cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          await delPowerStations(item.id);
          if (powerStationList.value.length === 1 && queryData.page > 1) {
            queryData.page = queryData.page - 1;
          }
          getpower();
          ElMessageBox({
            type: "success",
            message: ("licence.success"),
          });
        })
        .catch(() => {
          ElMessageBox({
            type: "info",
            message: ("licence.cancels"),
          });
          // getpower();
        });

      // getpower();
    }
    // 分页
    const handleSizeChange = (val:number) => {
      queryData.pageSize = val;
      getpower();
    }
    const handleCurrentChange = (val:number) =>  {
      queryData.page = val;
      getpower();
    }
    // // 数据曲线图
    const chart4=ref<HTMLElement>()
    const getTrendcurveData = (data:any) =>  {
      let dataArr1 = data.series[0].data;
      let dataArr2 = data.series[1].data;
      let intervalY1 = Math.ceil(Math.max(...dataArr1) / 6);
      let intervalY2 = Math.abs(Math.max(...dataArr2) / 6);
      option_chart4.value = {
        tooltip: {
          show: true,
          trigger: "axis",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: { itemHeight: 12, itemWidth: 12, icon: "circle" },
        grid: {
          left: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.categories,
        },
        yAxis: [
          {
            type: "value",
            name: data.series[0].unit,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              // 保留一位小数
              formatter: function (value:any) {
                return value.toFixed(1);
              },
            },
            min: 0,
            max: intervalY1 * 6, // 最大值
            splitNumber: 6, // 坐标轴的分割段数(预估值)
            interval: intervalY1, // 强制设置坐标轴分割间隔。
          },
          {
            type: "value",
            name: data.series[1].unit,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              // 保留一位小数
              formatter: function (value:any) {
                return value.toFixed(1);
              },
            },
            min: 0,
            max: intervalY2 * 6, // 最大值
            splitNumber: 6, // 坐标轴的分割段数(预估值)
            interval: intervalY2, // 强制设置坐标轴分割间隔。
          },
        ],
        series: [
          {
            name: data.series[0].name,
            data: data.series[0].data,
            type: "line",
            stack: "Total",
            symbol: "none",
            itemStyle: {
              normal: {
                color: "#5079F6",
                lineStyle: {
                  width: 1, //设置线条粗细
                },
              },
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(44,90,221)",
                },
                {
                  offset: 1,
                  color: "rgba(44,90,221,0)",
                },
              ]),
            },
            yAxisIndex: 0, //对应标签yAxis中的第一个数据
          },
          {
            name: data.series[1].name,
            data: data.series[1].data,
            type: "line",
            symbol: "none",
            itemStyle: {
              normal: {
                color: "#E28868",
                lineStyle: {
                  width: 1, //设置线条粗细
                },
              },
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgba(255,78,20)",
                },
                {
                  offset: 1,
                  color: "rgba(255,78,20,0)",
                },
              ]),
            },
            yAxisIndex: 1, //对应标签yAxis中的第二个数据
          },
        ],
      };
      let myChart_chart4:echarts.ECharts;
      nextTick(() => {
        myChart_chart4 = echarts.init(chart4.value as HTMLElement);
        myChart_chart4.setOption(option_chart4.value);
      });
      window.addEventListener("resize", function () {
        myChart_chart4.resize();
      });
    }
    onMounted(()=>{
        showCountry.value = auth.hasPermi('index:powerstaion:show')&&(localStorage.getItem("individual") as string == '1');
        individual.value = localStorage.getItem('individual') as string ;
        // 获取语言
        if (localStorage.getItem("locale") == "en_US") {
          lang.value = 1;
        } else {
          lang.value = 0;
        }
        // 获取电站信息
        powerStation.value = JSON.parse(localStorage.getItem("powerStation") as string);
        // 获取用户信息
        userInfo.value = JSON.parse(localStorage.getItem("userInfo") as string);

        // 查询按钮点击事件
        getpower();
        // 获取省市级
        getAdd('');
        //获取国家
        getCountry();

    })
</script>

<style scoped lang="scss">
* {
  margin: 0;
  //   padding: 0;
  box-sizing: border-box;
}

// 分页
.block {
  // display: flex;
  display: -webkit-box;
  justify-content: end;
}

.content {
  position: relative;
  width: 100%;
  background-color: #fff;
  padding: 20px 20px 30px 20px;
  border-radius: 6px;

  #title {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #0e1319;
    margin-bottom: 20px;
  }

  // 设备序列号
  .input {
    width: 200px;
    margin-left: 20px;
    margin-right: 20px;
  }

  // 查询按钮
  .el-button--primary {
    color: #ffffff;
    background-color: #305add;
    border-color: #305add;
  }

  // ========
  .time-box {
    margin: -20px 0 -10px -20px;
  }

  .content-main {
    padding-top: 20px;
    background: #f6f8fa;
  }

  // 曲线图
  .curveData {
    // position: absolute;
    // left: -9999pxc;
    width: 1000px !important;
    height: 350px;
  }

  .active {
    color: #305add;
  }
}

.expand {
  background: #f6f8fa;
  display: flex;
  width: 100%;
  height: 300px;
  padding: 0;

  .expand-left {
    width: 70%;
    height: 100%;
    // background-color: pink;
  }

  .expand-right {
    width: 30%;
    height: 100%;

    ul {
      padding: 0;
      display: flex;
      flex-wrap: wrap;

      .fault-content {
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        width: 190px;
        margin-bottom: 50px;

        // 左边图片
        .img-l {
          width: 50px;
          height: 50px;
          // background: #1267fa;
          // opacity: 0.2;
          border-radius: 9px;
          margin-right: 10px;

          img {
            width: 100%;
            height: 100%;
          }
        }

        // 右边内容
        .content-r {
          flex: 1;

          // 小标题
          .small-title {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #666666;
            line-height: 20px;
          }

          .number {
            font-size: 22px;
            font-family: DINAlternate-Bold, DINAlternate;
            font-weight: bold;
            color: #0e1319;
          }
        }
      }
    }
  }
}
 ::v-deep .el-table tr td
{
  &:last-child {
    .el-button--small{
      padding: 5px 2px !important;
    }
  }
}
</style>

<style>
.el-tooltip__popper {
  max-width: 40%;
}
</style>
